package com.hengfoxwolf.jetpackdemo.util
import android.app.Application

object ContextUtil {
    fun getCurrentApplication(): Application? {
        var application: Application? = null

        try {
            val preClazz = Class.forName("android.app.ActivityThread")
            val preMethod = preClazz.getDeclaredMethod("currentApplication")
            preMethod.isAccessible = true
            application = preMethod.invoke(null) as? Application
        } catch (_: Exception) {
        }

        if (application != null) {
            return application
        }

        try {
            val nextClazz = Class.forName("android.app.AppGlobals")
            val nextMethod = nextClazz.getDeclaredMethod("getInitialApplication")
            nextMethod.isAccessible = true
            application = nextMethod.invoke(null) as? Application
        } catch (_: Exception) {}

        return application
    }
}